<template>
  <div>
    <div class="components-img-upload">
      <ul
        v-if="img"
        class="el-upload-list el-upload-list--picture-card show-pic"
        @click="elxImgboxHandle"
      >
        <li
          tabindex="0"
          class="el-upload-list__item is-success"
        >
          <ImgShow
            :src="img"
            :img-style="{'object-fit':'contain'}"
          />
          <div
            v-if="img&&!disabled"
            tabindex="0"
            class="el-upload el-upload--picture-card blackba"
            @click.stop="detailImg"
          >
            <el-icon class="delete">
              <Delete />
            </el-icon>
          </div>
        </li>
      </ul>

      <div
        v-else
        tabindex="0"
        class="el-upload el-upload--picture-card"
        @click="elxImgboxHandle"
      >
        <el-icon><Plus /></el-icon>
      </div>
    </div>
    <!-- 弹窗, 新增图片 -->
    <elx-imgbox
      v-if="elxImgboxVisible"
      ref="elxImgboxRef"
      :max-size="props.maxSize"
      :img-size-limit="props.imgSizeLimit"
      @refresh-pic="refreshPic"
    />
  </div>
</template>

<script setup>
import { Delete, Plus } from '@element-plus/icons-vue'
const emit = defineEmits(['changeValue', 'update:modelValue'])

const props = defineProps({
  modelValue: {
    default: '',
    type: String
  },
  disabled: {
    default: false,
    type: Boolean
  },
  maxSize: {
    default: 2,
    type: Number
  },
  imgSizeLimit: {
    default: false,
    type: Boolean
  }
})
const elxImgboxRef = ref(null)
const img = ref(props.modelValue)
watch(
  () => props.modelValue,
  newVal => {
    img.value = newVal
  },
  { immediate: true }
)
// 打开图片选择窗
const elxImgboxVisible = ref(false)
const elxImgboxHandle = () => {
  if (props.disabled) return false
  elxImgboxVisible.value = true
  nextTick(() => {
    elxImgboxRef.value?.init(1)
  })
}
// 删除图片
const detailImg = () => {
  img.value = ''
  elxImgboxVisible.value = true
  nextTick(() => {
    elxImgboxRef.value?.onDelete()
  })
  emit('changeValue')
}

const refreshPic = imagePath => {
  img.value = imagePath
  emit('update:modelValue', imagePath)
}
defineExpose({ detailImg })
</script>

<style lang="scss" scoped>
.components-img-upload {
  position: relative;
  .pic-uploader-component .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .pic-uploader-component .el-upload:hover {
    border-color: #409eff;
  }

  .show-pic:hover .blackba {
    display: inline-block !important;
  }
  .delete {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  .blackba {
    display: none;
    position: absolute;
    background: rgba(0, 0, 0, 0.7) !important;
    left: 0;
    border: none !important;
  }
}
</style>
